package com.qkl.xiatang.app.web.controller;


import com.qkl.xiatang.app.dto.PageInDTO;
import com.qkl.xiatang.app.dto.feed.*;
import com.qkl.xiatang.app.dto.log.JobLogInDTO;
import com.qkl.xiatang.app.exception.BusinessException;
import com.qkl.xiatang.app.service.impl.FeedAllocService;
import com.qkl.xiatang.app.utils.AppUtils;
import com.qkl.xiatang.app.utils.ErrorCodeUtils;
import com.qkl.xiatang.app.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("{app.baseURL}")
@Slf4j
public class FeedAllocCotroller {

    @Autowired
    private FeedAllocService feedAllocService;


    /**
     * 查询存在喂料任务
     * @param webdto
     * @return
     */
    @PostMapping("/queryExistsFeedTask")
    public Result queryExistsFeedTask(@RequestBody FeedAllocAddWebDTO webdto) {
        log.info("====== queryExistsFeedTask FeedAllocAddWebDTO={}",webdto);
        if(!webdto.checkParams2()){
            return Result.error(ErrorCodeUtils.PARAM_ILLEGAL, ErrorCodeUtils.PARAM_ILLEGAL_MSG);
        }
        return ControllerHelper.toOperateResult(feedAllocService.queryExistsFeedTask(webdto));
    }


    /**
     *配料
     * @param webdto
     * @return
     */
    @PostMapping("/allocFeed")
    public Result addFeedAlloc(@RequestBody FeedAllocAddDTO webdto) {
        log.info("====== addFeedAlloc FeedAllocAddDTO={}",webdto);
        if(!webdto.checkParams()){
            return Result.error(ErrorCodeUtils.PARAM_ILLEGAL, ErrorCodeUtils.PARAM_ILLEGAL_MSG);
        }
        try {
            return ControllerHelper.toOperateResult(feedAllocService.addFeedAlloc(webdto));
        }catch (BusinessException e){
            return Result.error(ErrorCodeUtils.OPERATE_FAIL,e.getMessage());
        }catch (Exception e1){
            e1.printStackTrace();
            return Result.error(ErrorCodeUtils.OPERATE_FAIL,e1.getMessage());
        }
    }

    /**
     *配饲料
     * @param webdto
     * @return
     */
    @PostMapping("/addAllocFeed")
    public Result addFeedAllocNew(@RequestBody FeedAllocAddWebDTO webdto) {
        log.info("====== addFeedAlloc FeedAllocAddDTO={}",webdto);
        if(!webdto.checkParams()){
            return Result.error(ErrorCodeUtils.PARAM_ILLEGAL, ErrorCodeUtils.PARAM_ILLEGAL_MSG);
        }
        try {
            return ControllerHelper.toOperateResult(feedAllocService.addFeedAlloc(webdto));
        }catch (BusinessException e){
            return Result.error(ErrorCodeUtils.OPERATE_FAIL,e.getMessage());
        }catch (Exception e1){
            e1.printStackTrace();
            return Result.error(ErrorCodeUtils.OPERATE_FAIL,e1.getMessage());
        }
    }

    /**
     * 动保配料
     * @param webdto
     * @return
     */
    @PostMapping("/allocZoo")
    public Result addZooAlloc(@RequestBody ZooAllocAddDTO webdto) {
        if(!webdto.checkParams()){
            return Result.error(ErrorCodeUtils.PARAM_ILLEGAL, ErrorCodeUtils.PARAM_ILLEGAL_MSG);
        }
        try {
            return ControllerHelper.toOperateResult(feedAllocService.addZooAlloc(webdto));
        }catch (BusinessException e){
            return Result.error(ErrorCodeUtils.OPERATE_FAIL,e.getMessage());
        }catch (Exception e1){
            e1.printStackTrace();
            return Result.error(ErrorCodeUtils.OPERATE_FAIL,e1.getMessage());
        }
    }

    /**
     * 查询喂料任务
     * @param params
     * @return
     */
    @GetMapping("/queryFeedTask")
    public Result queryFeedTask(@RequestParam Map<String,Object> params) {
        String pondId = StringUtils.trimToEmpty((String) params.get("pondId"));
        log.info("controller queryFeedTask pondId={}",pondId);
        if(StringUtils.isEmpty(pondId)){
            return Result.error(ErrorCodeUtils.PARAM_EMPTY, ErrorCodeUtils.PARAM_EMPTY_MSG);
        }
        return ControllerHelper.toQueryResult(feedAllocService.queryFeedTask(pondId));
    }

    /**
     * 完成喂料任务
     * @param params
     * @return
     */
    @PostMapping("/finishFeedTask")
    public Result finishFeedTask(@RequestBody Map<String,Object> params) {
        String taskId = StringUtils.trimToEmpty((String) params.get("taskId"));
        if(StringUtils.isEmpty(taskId)){
            return Result.error(ErrorCodeUtils.PARAM_EMPTY, ErrorCodeUtils.PARAM_EMPTY_MSG);
        }
        return ControllerHelper.toOperateResult(feedAllocService.finishFeedTask(taskId));
    }

    /**
     * 完成虾料称料任务
     * @param params
     * @return
     */
    @PostMapping("/finishWeighFeedTask")
    public Result finishWeighFeedTask(@RequestBody Map<String,Object> params) {
        String taskId = StringUtils.trimToEmpty((String) params.get("taskId"));
        if(StringUtils.isEmpty(taskId)){
            return Result.error(ErrorCodeUtils.PARAM_EMPTY, ErrorCodeUtils.PARAM_EMPTY_MSG);
        }
        return ControllerHelper.toOperateResult(feedAllocService.finishWeighFeedTask(taskId));
    }

    /**
     * 完成虾料称料当天任务
     * @param params
     * @return
     */
    @PostMapping("/finishWeighFeedTaskToday")
    public Result finishWeighFeedTaskToday(@RequestBody Map<String,Object> params) {
        String pondId = StringUtils.trimToEmpty((String) params.get("pondId"));
        String taskId = StringUtils.trimToEmpty((String) params.get("taskId"));
        if(StringUtils.isAnyEmpty(taskId)){
            return Result.error(ErrorCodeUtils.PARAM_EMPTY, ErrorCodeUtils.PARAM_EMPTY_MSG);
        }
        return ControllerHelper.toOperateResult(feedAllocService.finishWeighFeedTaskToday(pondId,taskId));
    }

    /**
     * 取消喂料任务
     * @param params
     * @return
     */
    @PostMapping("/cancelFeedTask")
    public Result cancelFeedTask(@RequestBody Map<String,Object> params) {
        String taskId = StringUtils.trimToEmpty((String) params.get("taskId"));
        if(StringUtils.isEmpty(taskId)){
            return Result.error(ErrorCodeUtils.PARAM_EMPTY, ErrorCodeUtils.PARAM_EMPTY_MSG);
        }
        return ControllerHelper.toOperateResult(feedAllocService.cancelFeedTask(taskId));
    }

    /**
     * 查询动保任务
     * @param params
     * @return
     */
    @GetMapping("/queryZooTask")
    public Result queryZooTask(@RequestParam Map<String,Object> params) {
        String pondId = StringUtils.trimToEmpty((String) params.get("pondId"));
        if(StringUtils.isEmpty(pondId)){
            return Result.error(ErrorCodeUtils.PARAM_EMPTY, ErrorCodeUtils.PARAM_EMPTY_MSG);
        }
        return ControllerHelper.toQueryResult(feedAllocService.queryZooTask(pondId));
    }

    /**
     * 完成动保任务
     * @param params
     * @return
     */
    @PostMapping("/finishZooTask")
    public Result finishZooTask(@RequestBody Map<String,Object> params) {
        String taskId = StringUtils.trimToEmpty((String) params.get("taskId"));
        if(StringUtils.isEmpty(taskId)){
            return Result.error(ErrorCodeUtils.PARAM_EMPTY, ErrorCodeUtils.PARAM_EMPTY_MSG);
        }
        return ControllerHelper.toOperateResult(feedAllocService.finishZooTask(taskId));
    }

    /**
     *完成动保称料任务
     * @param params
     * @return
     */
    @PostMapping("/finishWeighZooTask")
    public Result finishWeighZooTask(@RequestBody Map<String,Object> params) {
        String taskId = StringUtils.trimToEmpty((String) params.get("taskId"));
        if(StringUtils.isEmpty(taskId)){
            return Result.error(ErrorCodeUtils.PARAM_EMPTY, ErrorCodeUtils.PARAM_EMPTY_MSG);
        }
        return ControllerHelper.toOperateResult(feedAllocService.finishWeighZooTask(taskId));
    }

    /**
     * 完成动保称料全部任务
     * @return
     */
    @PostMapping("/finishWeighZooTaskAll")
    public Result finishWeighZooTaskAll() {
        return ControllerHelper.toOperateResult(feedAllocService.finishWeighZooTaskAll());
    }

    /**
     * 查询动保未完成任务
     * @return
     */
    @GetMapping("/queryZooUnfinishTask")
    public Result queryZooUnfinishTask() {
        return ControllerHelper.toQueryResult(feedAllocService.queryZooUnfinishTask());
    }

    /**
     * 取消动保任务
     * @param params
     * @return
     */
    @PostMapping("/cancelZooTask")
    public Result cancelZooTask(@RequestBody Map<String,Object> params) {
        List<String> taskGroupIdList = (List<String>) params.get("taskGroupIdList");
        taskGroupIdList = AppUtils.stringsDistinct(taskGroupIdList);
        if(ObjectUtils.isEmpty(taskGroupIdList)){
            return Result.error(ErrorCodeUtils.PARAM_EMPTY, ErrorCodeUtils.PARAM_EMPTY_MSG);
        }
        return ControllerHelper.toOperateResult(feedAllocService.cancelZooTask(taskGroupIdList));
    }

    /**
     * 取消动保称料任务
     * @param params
     * @return
     */
    @PostMapping("/cancelZooWeighTask")
    public Result cancelZooWeighTask(@RequestBody Map<String,Object> params) {
        String taskId = StringUtils.trimToEmpty((String)params.get("taskId"));
        if(StringUtils.isEmpty(taskId)){
            return Result.error(ErrorCodeUtils.PARAM_EMPTY, ErrorCodeUtils.PARAM_EMPTY_MSG);
        }
        return ControllerHelper.toOperateResult(feedAllocService.cancelZooWeighTask(taskId));
    }

    /**
     * 查料台
     * @param webdto
     * @return
     */
    @PostMapping("/checkFeedAlloc")
    public Result checkFeedAlloc(@RequestBody FeedAllocCheckDTO webdto) {
        log.info("=======.checkFeedAlloc controller webdto={}",webdto);
        String pondId = StringUtils.trimToEmpty(webdto.getPondId());
        String taskId = StringUtils.trimToEmpty(webdto.getTaskId());
        String abnorMemo = StringUtils.trimToEmpty(webdto.getAbnorMemo());
        List<String> abnorImageList = AppUtils.stringsDistinct(webdto.getAbnorImageList());
        webdto.setTaskId(taskId);
        webdto.setPondId(pondId);
        webdto.setAbnorMemo(abnorMemo);
        webdto.setAbnorImageList(abnorImageList);
        if(StringUtils.isAllEmpty(pondId,taskId)){
            return Result.error(ErrorCodeUtils.PARAM_EMPTY, ErrorCodeUtils.PARAM_EMPTY_MSG);
        }
        Result result = ControllerHelper.toOperateResult(feedAllocService.checkFeedAlloc(webdto));
        log.info("=======.checkFeedAlloc controller result={}",result);
        return result;
    }

    /**
     * 工作日志查询
     * @param indto
     * @return
     */
    @PostMapping("/queryJobLog")
    public Result queryJobLog(@RequestBody JobLogInDTO indto) {
        queryJobLogParams(indto);
        return ControllerHelper.toQueryResult(feedAllocService.queryJobLog(indto));
    }

    /**
     * 工作日志下载
     * @param indto
     * @param response
     * @return
     */
    @PostMapping("/downloadJobLog")
    public Result downloadJobLog(@RequestBody JobLogInDTO indto,HttpServletResponse response) {
        queryJobLogParams(indto);
        ServletOutputStream outputStream = null;
        DownloadJobLogDTO download = feedAllocService.downloadJobLog(indto);
        try {
            String filename = URLEncoder.encode(download.getFilename(),"UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            //response.setContentType("multipart/form-data");
            response.setContentType("application/vnd.ms-excel");
            outputStream = response.getOutputStream();
            download.getWorkbook().write(outputStream);
            outputStream.flush();
            return null;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null != outputStream){
                try {
                    outputStream.close();
                }catch (Exception e1){}
            }
        }
        return Result.error(ErrorCodeUtils.OPERATE_FAIL,"日志下载失败");
    }
    private static void queryJobLogParams(JobLogInDTO indto){
        String startAllocDate = StringUtils.trimToEmpty(indto.getStartAllocDate());
        String endAllocDate = StringUtils.trimToEmpty(indto.getEndAllocDate());
        String logType = StringUtils.trimToEmpty(indto.getLogType());
        List<String> pondIdList = AppUtils.stringsDistinct(indto.getPondIdList());
        indto.setEndAllocDate(endAllocDate);
        indto.setPondIdList(pondIdList);
        indto.setStartAllocDate(startAllocDate);
        indto.setLogType(logType);
    }

    /**
     * 虾料配料信息查询
     * @param params
     * @return
     */
    @GetMapping("/queryShrimpAllocInfo")
    public Result queryShrimpAllocInfo(@RequestParam Map<String,Object> params) {
        String serialNo = StringUtils.trimToEmpty((String) params.get("serialNo"));
        FeedAllocQueryInDTO queryInDTO = new FeedAllocQueryInDTO();
        AppUtils.toPageInDTO(params,queryInDTO);
        queryInDTO.setSerialNo(AppUtils.parseInt(serialNo));
        return Result.success(feedAllocService.queryShrimpAllocInfo(queryInDTO),"虾料配料信息查询");
    }
    @PostMapping("/queryShrimpAllocInfo")
    public Result queryShrimpAllocInfoPost(@RequestBody FeedAllocQueryInDTO queryInDTO) {
        log.info("===queryShrimpAllocInfoPost.queryInDTO={}",queryInDTO);
        return Result.success(feedAllocService.queryShrimpAllocInfo(queryInDTO),"虾料配料信息查询");
    }

    /**
     *动保配料信息查询
     * @param params
     * @return
     */
    @GetMapping("/queryZooAllocInfo")
    public Result queryZooAllocInfo(@RequestParam Map<String,Object> params) {
        log.info("=======queryZooAllocInfo.params={}",params);
        String pondIdList = (String)params.get("pondIdList");
        String groupIdList = (String)params.get("groupIdList");

        FeedAllocQueryInDTO queryInDTO = new FeedAllocQueryInDTO();
        AppUtils.toPageInDTO(params,queryInDTO);
        queryInDTO.setPondIdList(AppUtils.stringToList(pondIdList));
        queryInDTO.setGroupIdList(AppUtils.stringToList(groupIdList));
        return Result.success(feedAllocService.queryZooAllocInfo(queryInDTO),"动保配料信息查询");
    }

    /**
     * 查询动保任务列表
     * @param params
     * @return
     */
    @GetMapping("/queryZooTaskList")
    public Result queryZooTaskList(@RequestParam Map<String,Object> params) {
        String taskGroupId = StringUtils.trimToEmpty((String) params.get("taskGroupId"));
        if(StringUtils.isEmpty(taskGroupId)){
            return Result.error(ErrorCodeUtils.PARAM_EMPTY, ErrorCodeUtils.PARAM_EMPTY_MSG);
        }
        return ControllerHelper.toQueryResult(feedAllocService.queryZooTaskList(taskGroupId));
    }

    /**
     * 查询未喂料列表
     * @return
     */
    @GetMapping("/queryUnfeedList")
    public Result queryUnfeedList() {
        return ControllerHelper.toQueryResult(feedAllocService.queryUnfeedList());
    }

    /**
     * 查询未喂料详情
     * @param params
     * @return
     */
    @GetMapping("/queryUnfeedDetail")
    public Result queryUnfeedDetail(@RequestParam Map<String,String> params) {
        String allocDate = StringUtils.trimToEmpty(params.get("allocDate"));
        String serialNo = StringUtils.trimToEmpty(params.get("serialNo"));
        Integer serialNum = AppUtils.parseInt(serialNo);
        return ControllerHelper.toQueryResult(feedAllocService.queryUnfeedDetail(allocDate,serialNum));
    }

    /**
     * 取消未喂料任务
     * @param params
     * @return
     */
    @PostMapping("/cancelUnfeedTask")
    public Result cancelUnfeedTask(@RequestBody Map<String,Object> params) {
        String allocDate = (String) params.get("allocDate");
        Integer serialNo = (Integer) params.get("serialNo");
        if(ObjectUtils.isEmpty(allocDate) || null == serialNo){
            return Result.error(ErrorCodeUtils.PARAM_EMPTY, ErrorCodeUtils.PARAM_EMPTY_MSG);
        }
        return ControllerHelper.toOperateResult(feedAllocService.cancelUnfeedTask(allocDate,serialNo));
    }

    /**
     * 获取查料时间
     * @param params
     * @return
     */
    @GetMapping("/getCheckFeedTime")
    public Result getCheckFeedTime(@RequestParam Map<String,Object> params) {
        String pondId = StringUtils.trimToEmpty((String) params.get("pondId"));
        return ControllerHelper.toQueryResult(feedAllocService.getCheckFeedTime(pondId));
    }

}
